
package org.rujue.common.persistence;

import com.github.pagehelper.PageInfo;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.rujue.common.config.Global;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 分页类
 * @author ThinkGem
 * @version 2013-7-2
 * @param <T>
 */

@Data
public class Page<T> extends PageInfo<T> {
	private int pageNo;

    /**
	 * 构造方法
	 * @param request 传递 repage 参数，来记住页码
	 * @param response 用于设置 Cookie，记住页码
	 */
	public Page(HttpServletRequest request, HttpServletResponse response){
		this(request, response, -2);
	}

	/**
	 * 构造方法
	 * @param request 传递 repage 参数，来记住页码
	 * @param response 用于设置 Cookie，记住页码
	 * @param defaultPageSize 默认分页大小，如果传递 -1 则为不分页，返回所有数据
	 */
	public Page(HttpServletRequest request, HttpServletResponse response, int defaultPageSize){
		// 获取 pageNum 参数，默认为 1
		String pageNumStr = request.getParameter("pageNo");
		int pageNum = 1;
		if (StringUtils.isNumeric(pageNumStr)) {
			pageNum = Integer.parseInt(pageNumStr);
		}

		// 获取 pageSize 参数，优先级：请求 > 默认配置 > defaultPageSize
		int pageSize;
		String pageSizeStr = request.getParameter("pageSize");
		if (StringUtils.isNumeric(pageSizeStr)) {
			pageSize = Integer.parseInt(pageSizeStr);
		} else if (defaultPageSize == -2) {
			pageSize = Integer.parseInt(Global.getConfig("pageSize")); // 从配置文件获取
		} else {
			pageSize = defaultPageSize > 0 ? defaultPageSize : 10; // 默认 fallback
		}
		this.setPageNum(pageNum);
		this.setPageSize(pageSize);
		this.setPageNo(pageNum);
	}


	public Page(List<T> list) {
		super(list);
		this.setPageNo(this.getPageNum());
	}

	public Page() {
		super();
	}
}
